// Server-side API helpers for Next.js App Router (RSC / Route Handlers)
// Strictly JWT via Authorization header (no cookies)

import {
  api,
  type CaptchaResponse,
  type LoginResponse,
  type MeResponse,
} from './api';

// Extract Bearer token from Authorization header string
export function bearerFromAuthorization(authorization?: string): string | undefined {
  if (!authorization) return undefined;
  const m = authorization.match(/^Bearer\s+(.+)$/i);
  return m ? m[1] : undefined;
}

export type ServerApiOptions = {
  token?: string;
  baseUrl?: string;
  headers?: Record<string, string>;
};

// Create a server-bound api instance with explicit token
export function serverApi(opts?: ServerApiOptions) {
  const token = opts?.token;
  const baseUrl = opts?.baseUrl;
  const headers = opts?.headers;
  return api.with({ token, baseUrl, headers });
}

// Typed Auth API for server usage (token must be provided explicitly when required)
export const ServerAuthApi = {
  captcha: () => serverApi().get<CaptchaResponse>('/api/auth/captcha'),
  login: (payload: {
    login: string;
    password: string;
    captchaId: string;
    captchaCode: string;
  }) => serverApi().post<LoginResponse>('/api/auth/login', payload),
  me: (token?: string) => serverApi({ token }).get<MeResponse>('/api/auth/me'),
};

// Guard to ensure user is authenticated in server components/actions
export async function requireUser(token?: string) {
  const res = await ServerAuthApi.me(token);
  if (!res.ok) {
    // Replace with redirect('/login') if desired in route handlers or RSC
    throw new Error('Unauthorized');
  }
  return res.data;
}

/**
 * Usage examples
 *
 * 1) Server Component:
 *   import { ServerAuthApi } from '@/lib/server-api';
 *   const meRes = await ServerAuthApi.me(bearerFromAuthorization(headers().get('authorization') ?? undefined));
 *
 * 2) Route Handler (app/api/foo/route.ts):
 *   import { serverApi, bearerFromAuthorization } from '@/lib/server-api';
 *   export async function GET(request: Request) {
 *     const token = bearerFromAuthorization(request.headers.get('authorization') || undefined);
 *     const { ok, data, error } = await serverApi({ token }).get('/ping');
 *     return Response.json(ok ? data : error, { status: ok ? 200 : (error?.status ?? 500) });
 *   }
 */